package com.csxy.systemmanager.service.impl;

import com.csxy.systemmanager.dao.MenuDao;
import com.csxy.systemmanager.dto.MenuDto;
import com.csxy.systemmanager.dto.RouteDto;
import com.csxy.systemmanager.entity.LoginUser;
import com.csxy.systemmanager.entity.Menu;
import com.csxy.systemmanager.common.ResponseResult;
import com.csxy.systemmanager.service.MenuService;
import com.csxy.systemmanager.utils.MenuTreeBuild;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service("MenuService")
public class MenuServiceImpl implements MenuService {
    // 注入dao
    @Autowired
    private MenuDao menuDao;
    @Override
    public ResponseResult getMenuTree() {
        //拿到当前用户
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long id = loginUser.getUser().getId();
        //根据id查出所有的菜单项
        List<Menu> menus = menuDao.selectMenusByUserId(id);
        //将菜单项变成树状结构
        List<MenuDto> menuDtos = MenuTreeBuild.buildMenuTree(menus);
        return new ResponseResult(200,"0k",menuDtos);
    }

    @Override
    public ResponseResult getRoutes() {
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long id = loginUser.getUser().getId();
        //根据id查出所有的菜单项
        List<Menu> menus = menuDao.selectMenusByUserId(id);
        List<RouteDto> routes = new ArrayList<>();
        //将对应的menus数据变成routes数据返回
        menus.stream().forEach(v->{
            routes.add(new RouteDto(v.getPath(),v.getMenuName(),v.getComponent(),true,null));
        });
        return new ResponseResult(200,"0k",routes);
    }
}
